﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Instrumentation;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using System.Reflection;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Web;
using System.Web.DynamicData;
using IntelFront.Attributes;
using Newtonsoft.Json;
using IntelFront.Models;
using AdminDbContext = IntelFront.Migrations.AdminDbContext;

namespace IntelFront.Controllers
{
    public class BaseController : Controller
    {
        protected TheContext db;

        public BaseController():base()
        {
            db = new TheContext();
        }

        /// <summary>
        /// 添加cookie存储数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="cookieName">cookie的名称</param>
        /// <param name="data">泛型数据</param>
        protected void AddDataCookie<T>(string cookieName,T data)
        {
            HttpCookie cookie = new HttpCookie(cookieName);
            //防止cookie.Value -> "\"\""
            cookie.Value = typeof(T) == typeof(string)? data.ToString() : JsonConvert.SerializeObject(data);
            Response.Cookies.Set(cookie);
        }

        /// <summary>
        /// 根据cookie获取数据
        /// </summary>
        /// <param name="name">cookie的名称</param>
        /// <returns>存储的已经转成json数据</returns>
        protected string GetDataCookie(string name)
        {
            HttpCookie cookie = Request.Cookies[name];
            if (cookie == null)
            {
                return null;
            }
            return cookie.Value;
        }

        /// <summary>
        /// 增加特殊的LoginCookie，后台加盐防止身份盗用
        /// </summary>
        /// <param name="data"></param>
        /// <param name="cookieName">默认为PIN</param>
        protected void AddLoginCookie(string data,string cookieName = "PIN")
        {
            HttpCookie cookie = new HttpCookie(cookieName);
            cookie.Value = Md5Crypto(data);
            Response.Cookies.Set(cookie);
        }

        /// <summary>
        /// 根据cookie得到唯一的PIN
        /// </summary>
        /// <returns></returns>
        protected string GetToken(string cookieName = "PIN")
        {
            HttpCookie cookie = Request.Cookies[cookieName];
            if (cookie.Value == null)
            {
                return null;
            }
            return cookie.Value;
        }

        /// <summary>
        /// 根据token添加用户session
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="PIN">唯一标识的PIN码</param>
        /// <param name="user">账户</param>
        protected void AddToken<TEntity>(string PIN,TEntity user) where TEntity : class
        {
            PIN = Md5Crypto(PIN);
            Session[PIN] = user;
        }

        /// <summary>
        /// 得到用户信息
        /// </summary>
        /// <returns>用户的对象</returns>
        protected object GetUserInfo()
        {
            string PIN = this.GetToken();
            if (PIN == null)
            {
                return null;
            }
            var user = Session[PIN];
            return user;
        }

        /// <summary>
        /// 这里var无法正确转换成User导致代码复用性差
        /// </summary>
        /// <param name="account"></param>
        /// <param name="pwd"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        protected int _Login(string account, string pwd , int type)
        {
            if (type == 2)
            {
                var user = db.Users.FirstOrDefault<User>(a => a.Account == account);
                if (user == null || user.Pwd != pwd)
                {
                    return 0;
                }
                user.Pwd = null;
                this.AddToken(user.Account, user);
                this.AddLoginCookie(user.Account);
                return 1;
            }
            else if(type == 1)
            {
                var user = db.Admins.FirstOrDefault<Admin>(a => a.Account == account);
                if (user == null || user.Pwd != pwd)
                {
                    return 0;
                }
                this.AddToken(user.Account, user);
                this.AddLoginCookie(user.Account);
                return 1;
            }
            return 0;
        }

        public virtual string UnLoginedRedirectUrl
        {
            get
            {
                return "/Auth/Index";
            }
        }

        protected enum UserTypeEnum
        {
            Admin = 1,
            User = 2
        }

        //todo: 修改成PersonEx增加代码复用
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            _Login("user1","123456",2);
            var attribute = filterContext.ActionDescriptor.GetCustomAttributes(typeof(PublicAttribute), false);
            if (attribute.Length == 0)
            {
                var user = this.GetUserInfo();
                var adminAttr = filterContext.ActionDescriptor.GetCustomAttributes(typeof (AdminAttribute), false);
                if (adminAttr.Length == 0)
                {
                    user =  user as User;
                    if (user == null)
                    {
                        filterContext.Result = new RedirectResult(this.UnLoginedRedirectUrl);
                    }
                }
                else
                {
                    Admin admin =  user as Admin;
                    if (admin == null || admin.Type != 1)
                    {
                        filterContext.Result = new RedirectResult(this.UnLoginedRedirectUrl);
                    }
                } 
            }
            base.OnActionExecuting(filterContext);
        }

        protected string Md5Crypto(string data)
        {
            byte[] buffer = Encoding.Default.GetBytes(data);
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] output = md5.ComputeHash(buffer);
            string result = BitConverter.ToString(output).Replace("-", "");
            return result;
        }
    }
    
}
